package com.jmlong.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jmlong.dao.BookDao;
import com.jmlong.dao.CommodityDao;
import com.jmlong.domain.*;
import com.jmlong.service.CommodityService;
import com.jmlong.service.UserService;
import com.jmlong.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CommodityServiceImpl implements CommodityService {

    @Autowired
    CommodityDao commodityDao;

    @Autowired
    UserService userService;

    @Autowired
    BookDao bookDao;

    @Override
    public JSONArray getAllCommodity(Integer pageNum, Integer pageSize) {
        JSONArray records = new JSONArray();
        JSONArray finalRecords = new JSONArray();
        JSONObject finalRecord = new JSONObject();
        PageHelper.startPage(pageNum,pageSize);
        Page<Commdity> allCommodity = commodityDao.getAllCommodity();
        if (allCommodity.size()==0){
            return finalRecords;
        }
        for (Commdity info:allCommodity) {
            JSONObject record = new JSONObject();
            String uuid = info.getCommodityID();
            List<CommodityImg> imgs = commodityDao.getMerchantCommodityImg(uuid);
            String img = "";
            if (imgs.size()==0){
                img = "/img/commodityImg/default.png";
            }else{
                img = imgs.get(0).getImg();
            }
            record.put("uuid",info.getCommodityID());
            record.put("name",info.getName());
            record.put("img",img);
            record.put("price",info.getPrice());
            record.put("time",info.getCollectionDate());
            record.put("commodityType",info.getCommodityType());
            records.add(record);
        }

        finalRecord.put("data",records);
        finalRecord.put("total",allCommodity.getTotal());
        finalRecord.put("pages",allCommodity.getPages());
        finalRecord.put("pageSize",allCommodity.getPageSize());
        finalRecord.put("pageNum",allCommodity.getPageNum());
        finalRecords.add(finalRecord);
        int a = 1;
        return finalRecords;
    }


    @Override
    public JSONArray getCommodityChooseType(Integer pageNum, Integer pageSize, String commodityType) {
        JSONArray records = new JSONArray();
        JSONArray finalRecords = new JSONArray();
        JSONObject finalRecord = new JSONObject();
        PageHelper.startPage(pageNum,pageSize);
        Page<Commdity> commodityPages = commodityDao.getCommodityChooseType(commodityType);
        if (commodityPages.size()==0){
            return finalRecords;
        }
        for (Commdity info:commodityPages) {
            JSONObject record = new JSONObject();
            String uuid = info.getCommodityID();
            List<CommodityImg> imgs = commodityDao.getMerchantCommodityImg(uuid);
            String img = "";
            if (imgs.size()==0){
                img = "/img/commodityImg/default.png";
            }else{
                img = imgs.get(0).getImg();
            }
            record.put("uuid",info.getCommodityID());
            record.put("name",info.getName());
            record.put("img",img);
            record.put("price",info.getPrice());
            record.put("time",info.getCollectionDate());
            record.put("commodityType",info.getCommodityType());
            records.add(record);
        }
        finalRecord.put("data",records);
        finalRecord.put("total",commodityPages.getTotal());
        finalRecord.put("pages",commodityPages.getPages());
        finalRecord.put("pageSize",commodityPages.getPageSize());
        finalRecord.put("pageNum",commodityPages.getPageNum());
        finalRecords.add(finalRecord);

        return finalRecords;
    }

    @Override
    public JSONArray searchCommodity(Integer pageNum, Integer pageSize,String searchName) {
        JSONArray records = new JSONArray();
        JSONArray finalRecords = new JSONArray();
        JSONObject finalRecord = new JSONObject();
        PageHelper.startPage(pageNum,pageSize);

        Page<Commdity> searchList = commodityDao.searchCommodity(searchName);
        if (searchList.size()==0){
            return finalRecords;
        }
        for (Commdity info:searchList) {
            JSONObject record = new JSONObject();
            String uuid = info.getCommodityID();
            List<CommodityImg> imgs = commodityDao.getMerchantCommodityImg(uuid);
            String img = "";
            if (imgs.size()==0){
                img = "/img/commodityImg/default.png";
            }else{
                img = imgs.get(0).getImg();
            }
            record.put("uuid",info.getCommodityID());
            record.put("name",info.getName());
            record.put("img",img);
            record.put("price",info.getPrice());
            record.put("time",info.getCollectionDate());
            record.put("commodityType",info.getCommodityType());
            records.add(record);
        }
        finalRecord.put("data",records);
        finalRecord.put("total",searchList.getTotal());
        finalRecord.put("pages",searchList.getPages());
        finalRecord.put("pageSize",searchList.getPageSize());
        finalRecord.put("pageNum",searchList.getPageNum());
        finalRecords.add(finalRecord);

        return finalRecords;

    }

    @Override
    public Integer imsertCommodityImg(CommodityImg commodityImg) {
        return commodityDao.imsertCommodityImg(commodityImg);
    }

    @Override
    public Integer deleteImg(String fileName) {

        return commodityDao.deleteImg(fileName);
    }

    @Override
    public Integer addCommodity(Commdity commdity) {
        return commodityDao.addCommodity(commdity);
    }

    @Override
    public List<Commdity> getMerchantCommodity(String merchantID) {
        return commodityDao.getMerchantCommodity(merchantID);
    }

    @Override
    public JSONArray getMerchantCommodityImg(List<Commdity> commdityList) {
        JSONArray records = new JSONArray();
        for (Commdity commodity:commdityList) {
            JSONObject record = new JSONObject();
            String commodityID=commodity.getCommodityID();
            List<CommodityImg> imgList = commodityDao.getMerchantCommodityImg(commodityID);
            String img = "";
            if (imgList.size()==0){
                img = "/img/commodityImg/default.png";
            }else{
                img = imgList.get(0).getImg();
            }
            record.put("uuid",commodity.getCommodityID());
            record.put("name",commodity.getName());
            record.put("img",img);
            record.put("price",commodity.getPrice());
            record.put("count",commodity.getCount());
            record.put("time",commodity.getCollectionDate());
            record.put("commodityType",commodity.getCommodityType());
            records.add(record);

        }
        return records;
    }

    @Override
    public JSONArray getCommodityDetail(String commdityID) {

        JSONArray records = new JSONArray();
        JSONObject record = new JSONObject();
        Commdity info = commodityDao.getCommodityInfo(commdityID);
        User merchantInfo = userService.getUserInfoById(info.getMerchantID());
        String merchantName = merchantInfo.getName();
        if (info==null){
            return null;
        }
        List<CommodityImg> imgs = commodityDao.getMerchantCommodityImg(commdityID);
        record.put("data",info);
        record.put("imgList",imgs);
        record.put("merchantName",merchantName);
        records.add(record);

        return records;
    }

    @Override
    public Integer updateCommodityDetail(String uuid,String name, String price, String describe,String commodityType,String count) {
        Commdity commdity = new Commdity();
        commdity.setCommodityID(uuid);
        commdity.setName(name);
        commdity.setPrice(price);
        commdity.setDescribe(describe);
        commdity.setCount(count);
        commdity.setCommodityType(commodityType);

        return commodityDao.updateCommodityDetail(commdity);

    }

    @Override
    public Integer deleteCommodity(String uuid) {
        String path = "D:\\GraduationJava\\src\\main\\resources\\static\\assest\\img\\commodityImg";

        List<BookItem> bookItemFlag = bookDao.getBookItemByCommodityID(uuid);
        if (bookItemFlag!=null && bookItemFlag.size()>0){
            Integer res = commodityDao.updateStatus(uuid);
            if (res!=0){
                log.info("商品在订单信息中存在，更改商品状态为下架！");
                return 1;
            }else {
                return 0;
            }
        }

        Integer result = commodityDao.deleteCommodity(uuid);
        if (result==1){
            log.info("商品信息删除成功！");
            List<CommodityImg> imgList = commodityDao.selectAllImg(uuid);
            for (CommodityImg imgs:imgList) {
                try{
                    String img = imgs.getImg();
                    String fileName = img.substring(img.lastIndexOf("/")+1);
                    File targetFile = new File(path);
                    File deleteFile = new File(targetFile, fileName);
                    boolean delFlag = deleteFile.delete();
                    if (delFlag){
                        log.info("商品资源本地目录下删除成功！");
                        result = commodityDao.deleteImg(fileName);
                    }else{
                        log.info("商品资源本地目录下删除失败！");
                        result = commodityDao.deleteImg(fileName);
                    }
                    if (result==1){
                        log.info("商品图片信息同步数据库删除成功！");
                    }else{
                        log.info("商品图片信息同步数据库删除失败！");
                    }
                }catch (Exception e) {
                    continue;
                }
            }
            commodityDao.delCommodityGrow(uuid);

        }else{
            return 0;
        }

        return 1;
    }

    @Override
    public Integer addCommodityGrowup(Map params) {

        String uuid = (String) params.get("uuid");
        String growthCycle = (String) params.get("growthCycle");
        String lightDuration = (String) params.get("lightDuration");
        String temperature = (String) params.get("temperature");
        String soilPH = (String) params.get("soilPH");
        String pesticideDose = (String) params.get("pesticideDose");
        String otherDescription = (String) params.get("otherDescription");
        String growUp = (String) params.get("growUp");

        CommodityGrowUp commodityGrowUp = new CommodityGrowUp();
        commodityGrowUp.setCommodityId(uuid);
        commodityGrowUp.setGrowthCycle(growthCycle);
        commodityGrowUp.setLightDuration(lightDuration);
        commodityGrowUp.setTemperature(temperature);
        commodityGrowUp.setSoilPH(soilPH);
        commodityGrowUp.setPesticideDose(pesticideDose);
        commodityGrowUp.setOtherDescription(otherDescription);
        commodityGrowUp.setGrowUp(growUp);
        commodityGrowUp.setCollectionDate(DateUtil.getCollectionDate());

        return commodityDao.addCommodityGrowup(commodityGrowUp);
    }

    @Override
    public List<CommodityGrowUp> getCommodityGrowUp(Map params) {

        String uuid = (String) params.get("uuid");
        String growUp = (String) params.get("GrowUp");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<CommodityGrowUp> list = commodityDao.getCommodityGrowUp(uuid,growUp);
        return list;
    }



    @Override
    public List<CommodityType> getCommodityType() {
        return commodityDao.getCommodityType();
    }


}
